package com.sky.task;

import com.sky.constant.MessageConstant;
import com.sky.constant.OrderConstant;
import com.sky.dto.OrderPageQueryDTO;
import com.sky.entity.Order;
import com.sky.mapper.OrderMapper;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 订单定时自动处理类
 *
 * @Author Vsunks.v
 * @Date 2023/5/12 10:08
 * @Blog blog.sunxiaowei.net/996.mba
 * @Description: 订单定时自动处理类
 */
@Slf4j
@Component
public class OrderTask {

    @Autowired
    OrderMapper orderMapper;

    /**
     * 处理超时未支付的订单
     */
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeoutOrder() {
        log.info("定时任务：开始处理超时未支付的订单，处理动作：取消");
        // 根据状态查询所有处于待支付的订单，下单时间要在15分钟之前
        // 组织查询条件
        OrderPageQueryDTO orderQueryDTO = OrderPageQueryDTO.builder()
                .status(OrderConstant.PENDING_PAYMENT)
                .endTime(LocalDateTime.now().minusMinutes(15))
                .build();


        List<Order> orders = orderMapper.listByConditions(orderQueryDTO);

        // 遍历订单集合，挨个设置状态为已取消
        if (orders != null && orders.size() > 0) {
            orders.forEach(order -> {
                order.setStatus(OrderConstant.CANCELLED);
                order.setCancelReason(MessageConstant.ORDER_CANCLE_BY_TIMEOUT);
                order.setCancelTime(LocalDateTime.now());
                orderMapper.updateById(order);
            });
        }

    }


    /**
     * 处理长期处于“派送中”的订单
     */
    @Scheduled(cron = "0 39 10 * * ?")
    public void processDeliveryOrder() {
        log.info("定时任务：开始处理处理长期处于“派送中”的订单，处理动作：设置为完成");
        // 根据状态查询所有处于派送中的订单，预计送达时间1个小时以后还处于派送中的订单
        // 组织查询条件
        OrderPageQueryDTO orderQueryDTO = OrderPageQueryDTO.builder()
                .status(OrderConstant.DELIVERY_IN_PROGRESS)
                .endTime(LocalDateTime.now().minusHours(1))
                .build();
        List<Order> orders = orderMapper.listByConditions(orderQueryDTO);

        // 遍历订单集合，挨个设置状态为已取消
        if (orders != null && orders.size() > 0) {
            orders.stream().forEach(order -> {
                order.setStatus(OrderConstant.COMPLETED);
                order.setDeliveryTime(LocalDateTime.now());
                orderMapper.updateById(order);
            });

        }
    }
}
